package com.qf.controller;

import com.qf.common.R;
import com.qf.constatns.AuthConstatns;
import com.qf.constatns.CarConstants;
import com.qf.constatns.RabbitMQConstatns;
import com.qf.constatns.RedisConstant;
import com.qf.feign.api.CarService;
import com.qf.feign.api.UserService;
import com.qf.utils.PassWordUtils;
import com.qf.vo.Customer;
import com.qf.vo.Sms;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CarService carService;

    @PostMapping("/checkUsername")
    @ResponseBody
    public Map<String, Object> checkUsername(String param) {

        Map<String, Object> map = new HashMap<>();

        // 1.检查用户名是否存在
        Customer customer = userService.getUserByName(param);

        // 2.判断
        if (customer == null) {
            map.put("status", "y");
            map.put("info", "可以注册");
        } else {
            map.put("status", "n");
            map.put("info", "用户名已经被注册了，请更换。");
        }
        return map;
    }

    @GetMapping("/sendSms/{phone}")
    @ResponseBody
    public void sendSms(@PathVariable String phone) {
        log.debug("{}", phone);

        // 1.生成验证码
        String code = RandomStringUtils.random(6, false, true);

        // 2.把验证码保存到reids中
        stringRedisTemplate.opsForValue().set(RedisConstant.AUTH_REGISTER_SMS_PRE + phone, code, 60, TimeUnit.SECONDS);

        // 3.发送短信
        Sms sms = new Sms();
        sms.setPhone(phone);
        sms.setCode(code);
        rabbitTemplate.convertAndSend(RabbitMQConstatns.SEND_MESSAGE_EXCHANGE, "send.sms.phone", sms);
        log.debug("短信发送完成 {}", sms);

    }

    @PostMapping("/registerUser")
    @ResponseBody
    public R registerUser(Customer customer) {
        log.debug("{}", customer);

        // 1.后台要做验证(后台不能太相信前台传递过来的数据)

        // 2.做验证码的校验
        String code = customer.getCode();
        String phone = customer.getPhone();

        // 3.查询用户存在redis中的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(RedisConstant.AUTH_REGISTER_SMS_PRE + phone);

        if (StringUtils.isEmpty(redisCode)) {
            return R.error("验证码已过期，请重新获取");
        }

        if (!redisCode.equals(code)) {
            return R.error("验证有误，请重新输入");
        }

        // 密码加密
        customer.setPassword(PassWordUtils.hashpw(customer.getPassword()));
        // 3.插入用户
        Boolean aBoolean = userService.addUser(customer);
        return R.success(aBoolean);
    }

    @PostMapping("/login")
    @ResponseBody
    public R login(String username, String password,
                   HttpServletRequest request,
                   @CookieValue(name = CarConstants.ANNO_CAR_COOKIE_NAME, defaultValue = "") String annoId) {

        // 1.根据用户名查询对象
        Customer customer = userService.getUserByName(username);

        // 2.判断非空,对比密码
        if (customer == null || !PassWordUtils.checkpw(password, customer.getPassword())) {
            return R.error("用户名获密码错误");
        }

        // 3.认证成功
        request.getSession().setAttribute(AuthConstatns.AUTH_SESSION, customer);

        // 合并购物车
        if (!StringUtils.isEmpty(annoId)) {
//            carService.mergeCar(customer.getId(), annoId);
        }

        // 4.返回成功
        return R.success();
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 注销session
        return "redirect:http://localhost/auth/login.html";
    }


    public static void main(String[] args) {


        // $2a$10$I1xX.XIzCs6LELvOui2R8.tkdBukMDqQghreZWZlwsnoDeZiqa0sO
        // $2a$10$pA57X0a.uWrgu6E70gbwxOsA/ZCUCdcz4L8FF90bC/2FYu2JUDHha
        String pw = "$2a$10$I1xX.XIzCs6LELvOui2R8.tkdBukMDqQghreZWZlwsnoDeZiqa0sO";

        // 1.第一个参数是明文
        // 2.第二个参数是盐值(唯一)
        String gensalt = BCrypt.gensalt(); // 获取盐值
        String hashpw = BCrypt.hashpw("123456", gensalt);
        System.out.println(gensalt);
        System.out.println(hashpw);

        //  对比
        boolean checkpw = BCrypt.checkpw("123456", pw);
        System.out.println(checkpw);
    }
}
